package com.wwg.base.serializable;

import com.alibaba.fastjson.JSON;

import java.io.*;


/**
 * @Description: 测试自定义序列化类的实现
 * @Param:
 * @return:
 * @Author: wwg
 * @Date: 2021/8/1
 */
public class ExternalizedUser implements Externalizable {

    @Override
    public String toString() {
        return "ExternalizedUser{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    private transient String name;
    private transient int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(name);
//        out.writeObject(age);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = (String) in.readObject();
//        age = (int) in.readObject();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ExternalizedUser externalizedUser = new ExternalizedUser();
        externalizedUser.setName("James");
        externalizedUser.setAge(11);

        System.out.println("序列化前：" + externalizedUser);
        // 序列化
        String filePath = "D:\\ideaWorkSpace\\weigang_wu\\test-util-springboot\\src\\main\\java\\com\\wwg\\base\\serializable\\.1.txt";
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(externalizedUser);

        // 反序列化
        FileInputStream fileInputStream = new FileInputStream(filePath);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        ExternalizedUser o = (ExternalizedUser)objectInputStream.readObject();

        System.out.println("反序列化后：" + o);
    }
}
